<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Device extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'devices';

    protected $fillable = ['floor_id', 'room_id', 'area_id', 'account', 'name', 'password', 'network', 'type', 'status', 'extra_data', 'remarks', 'lose_at'];

    protected $casts = [
        'extra_data' => 'array'
    ];

    protected $appends = ['status_text', 'type_text'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function floor()
    {
        return $this->belongsTo(Floor::class, 'floor_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function room()
    {
        return $this->belongsTo(Room::class, 'room_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function area()
    {
        return $this->belongsTo(Area::class, 'area_id');
    }


    public function branch()
    {
        return $this->hasMany(DeviceBranch::class, 'device_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function device485()
    {
        return $this->belongsToMany(Device485Model::class, 'device_485', 'device_id', 'model_id');
    }

    public function getStatusTextAttribute()
    {
        return $this->status ? '正常' : '失去链接';
    }

    public function getTypeTextAttribute()
    {
        $typeName = '';
        switch ($this->type) {
            case 1:
                $typeName = '网关';
                break;
            case 2:
                $typeName = '智能开关';
                break;
            default:
                $typeName = '未知类型'; // 默认情况，以防没有匹配的
        }
        return $typeName;
    }


}
